Method of Python calling C language [Based on ctypes module]

  • 2020-07-21 08:57:18
  • OfStack

This article gives an example of how Python calls the C language. To share for your reference, specific as follows:

The ctypes module in Python is probably one of the simplest Python calls to the C method. The ctypes module provides data types and functions compatible with the C language to load dll files, so no changes to the source files are required when invoked. That's what makes this approach so simple.

The sample is as follows

C code that implements the sum of two Numbers, save as ES17en.c


//sample C file to add 2 numbers - int and floats
#include <stdio.h>
int add_int(int, int);
float add_float(float, float);
int add_int(int num1, int num2){
  return num1 + num2;
}
float add_float(float num1, float num2){
  return num1 + num2;
}

Next, the C file is compiled to a.so file (windows). The following action generates the adder.so file


#For Linux
$ gcc -shared -Wl,-soname,adder -o adder.so -fPIC add.c
#For Mac
$ gcc -shared -Wl,-install_name,adder.so -o adder.so -fPIC add.c
#For windows
$
gcc -shared -Wl,-soname,adder -o adder.dll -fPIC add.c

Now call it in your Python code


from ctypes import *
#load the shared object file
adder = CDLL('./adder.so')
#Find sum of integers
res_int = adder.add_int(4,5)
print "Sum of 4 and 5 = " + str(res_int)
#Find sum of floats
a = c_float(5.5)
b = c_float(4.1)
add_float = adder.add_float
add_float.restype = c_float
print "Sum of 5.5 and 4.1 = ", str(add_float(a, b))

The output is as follows


Sum of 4 and 5 = 9
Sum of 5.5 and 4.1 = 9.60000038147

In this example, the C file is self-explanatory and contains two functions that implement an integer sum and a floating point sum, respectively.

In the Python file, 1 starts the ctypes module, then USES the CDLL function to load the library file we created. This allows us to use the functions in the C library with the variable adder. when adder.add_int() When invoked, an internal call to the C function add_int is made. The ctypes interface allows us to use the default string and integer types in the native Python when calling the C function.

For other types such as Boolean and floating-point, you must use the correct ctype type. As to the adder.add_float() When the function passes arguments, we first convert the decimal value in Python to type c_float before passing it to the C function. This method is simple and clear, but very limited. For example, objects cannot be manipulated in C.

More about Python related content interested readers to view this site project: "Python process and thread skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for Python programming.


Related articles: